<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>系统配置</span>
          <el-button 
            type="primary" 
            @click="saveSettings" 
            :loading="isSaving"
            v-hasPermi="['system:config:edit']"
          >
            保存配置
          </el-button>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" class="settings-tabs">
        <!-- 基本配置 -->
        <el-tab-pane label="基本配置" name="basic">
          <el-form 
            ref="basicFormRef" 
            :model="basicSettings" 
            :rules="basicRules" 
            label-width="120px" 
            class="settings-form"
          >
            <el-form-item label="API 端点" prop="apiEndpoint">
              <el-input v-model="basicSettings.apiEndpoint" placeholder="请输入API端点地址" />
              <div class="form-tip">API服务的访问地址，默认：http://localhost:5000/api</div>
            </el-form-item>
            
            <el-form-item label="扫描超时时间" prop="scanTimeout">
              <el-input-number 
                v-model="basicSettings.scanTimeout" 
                :min="1" 
                :max="360" 
                :step="5"
                controls-position="right"
                placeholder="请输入扫描超时时间"
              />
              <span class="unit"> 分钟</span>
              <div class="form-tip">扫描任务的最大执行时间，超过此时间将自动终止</div>
            </el-form-item>
            
            <el-form-item label="结果自动刷新" prop="autoRefresh">
              <el-switch v-model="basicSettings.autoRefresh" />
              <div class="form-tip">开启后，扫描结果页面将自动刷新</div>
            </el-form-item>
            
            <el-form-item label="自动刷新间隔" prop="refreshInterval" :required="basicSettings.autoRefresh">
              <el-input-number 
                v-model="basicSettings.refreshInterval" 
                :min="5" 
                :max="300" 
                :step="5"
                controls-position="right"
                placeholder="请输入自动刷新间隔"
                :disabled="!basicSettings.autoRefresh"
              />
              <span class="unit"> 秒</span>
              <div class="form-tip">自动刷新的时间间隔，仅在开启自动刷新时有效</div>
            </el-form-item>
            
            <el-form-item label="结果保留天数" prop="resultRetentionDays">
              <el-input-number 
                v-model="basicSettings.resultRetentionDays" 
                :min="1" 
                :max="365" 
                :step="1"
                controls-position="right"
                placeholder="请输入结果保留天数"
              />
              <span class="unit"> 天</span>
              <div class="form-tip">扫描结果的保留时间，超过此时间的结果将被自动清理</div>
            </el-form-item>
            
            <el-form-item label="主题模式" prop="themeMode">
              <el-radio-group v-model="basicSettings.themeMode">
                <el-radio label="light">浅色模式</el-radio>
                <el-radio label="dark">深色模式</el-radio>
                <el-radio label="auto">跟随系统</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 扫描配置 -->
        <el-tab-pane label="扫描配置" name="scan">
          <el-form 
            ref="scanFormRef" 
            :model="scanSettings" 
            :rules="scanRules" 
            label-width="120px" 
            class="settings-form"
          >
            <el-form-item label="默认扫描深度" prop="defaultScanDepth">
              <el-input-number 
                v-model="scanSettings.defaultScanDepth" 
                :min="1" 
                :max="5" 
                :step="1"
                controls-position="right"
                placeholder="请输入默认扫描深度"
              />
              <div class="form-tip">扫描的深度级别，数字越大，扫描越全面但耗时越长</div>
            </el-form-item>
            
            <el-form-item label="并发扫描数" prop="concurrentScans">
              <el-input-number 
                v-model="scanSettings.concurrentScans" 
                :min="1" 
                :max="20" 
                :step="1"
                controls-position="right"
                placeholder="请输入并发扫描数"
              />
              <div class="form-tip">同时执行的最大扫描任务数</div>
            </el-form-item>
            
            <el-form-item label="请求超时时间" prop="requestTimeout">
              <el-input-number 
                v-model="scanSettings.requestTimeout" 
                :min="5" 
                :max="60" 
                :step="5"
                controls-position="right"
                placeholder="请输入请求超时时间"
              />
              <span class="unit"> 秒</span>
              <div class="form-tip">单个HTTP请求的超时时间</div>
            </el-form-item>
            
            <el-form-item label="重试次数" prop="retryCount">
              <el-input-number 
                v-model="scanSettings.retryCount" 
                :min="0" 
                :max="5" 
                :step="1"
                controls-position="right"
                placeholder="请输入重试次数"
              />
              <div class="form-tip">请求失败后的重试次数</div>
            </el-form-item>
            
            <el-form-item label="User-Agent" prop="userAgent">
              <el-input v-model="scanSettings.userAgent" placeholder="请输入User-Agent" />
              <div class="form-tip">扫描请求使用的User-Agent头部</div>
            </el-form-item>
            
            <el-form-item label="启用代理" prop="useProxy">
              <el-switch v-model="scanSettings.useProxy" />
              <div class="form-tip">是否通过代理服务器发送扫描请求</div>
            </el-form-item>
            
            <el-form-item label="代理服务器" prop="proxyServer" :required="scanSettings.useProxy">
              <el-input 
                v-model="scanSettings.proxyServer" 
                placeholder="请输入代理服务器地址"
                :disabled="!scanSettings.useProxy"
              />
              <div class="form-tip">格式：http://username:password@host:port</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 通知配置 -->
        <el-tab-pane label="通知配置" name="notification">
          <el-form 
            ref="notificationFormRef" 
            :model="notificationSettings" 
            :rules="notificationRules" 
            label-width="120px" 
            class="settings-form"
          >
            <el-form-item label="扫描完成通知" prop="notifyOnScanComplete">
              <el-switch v-model="notificationSettings.notifyOnScanComplete" />
              <div class="form-tip">扫描任务完成后发送通知</div>
            </el-form-item>
            
            <el-form-item label="高风险漏洞通知" prop="notifyHighRisk">
              <el-switch v-model="notificationSettings.notifyHighRisk" />
              <div class="form-tip">发现高风险漏洞时发送通知</div>
            </el-form-item>
            
            <el-form-item label="邮件通知" prop="emailNotification">
              <el-switch v-model="notificationSettings.emailNotification" />
              <div class="form-tip">是否通过邮件发送通知</div>
            </el-form-item>
            
            <el-form-item label="通知邮箱" prop="notificationEmail" :required="notificationSettings.emailNotification">
              <el-input 
                v-model="notificationSettings.notificationEmail" 
                placeholder="请输入通知邮箱地址"
                :disabled="!notificationSettings.emailNotification"
              />
              <div class="form-tip">接收通知的邮箱地址</div>
            </el-form-item>
            
            <el-form-item label="Webhook通知" prop="webhookNotification">
              <el-switch v-model="notificationSettings.webhookNotification" />
              <div class="form-tip">是否通过Webhook发送通知</div>
            </el-form-item>
            
            <el-form-item label="Webhook URL" prop="webhookUrl" :required="notificationSettings.webhookNotification">
              <el-input 
                v-model="notificationSettings.webhookUrl" 
                placeholder="请输入Webhook URL"
                :disabled="!notificationSettings.webhookNotification"
              />
              <div class="form-tip">接收通知的Webhook地址</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- AI配置 -->
        <el-tab-pane label="AI配置" name="ai">
          <el-form 
            ref="aiFormRef" 
            :model="aiSettings" 
            :rules="aiRules" 
            label-width="120px" 
            class="settings-form"
          >
            <el-form-item label="启用AI分析" prop="enableAiAnalysis">
              <el-switch v-model="aiSettings.enableAiAnalysis" />
              <div class="form-tip">是否启用AI辅助漏洞分析和修复建议生成</div>
            </el-form-item>
            
            <el-form-item label="AI模型类型" prop="aiModelType" :required="aiSettings.enableAiAnalysis">
              <el-select 
                v-model="aiSettings.aiModelType" 
                placeholder="请选择AI模型类型"
                :disabled="!aiSettings.enableAiAnalysis"
              >
                <el-option label="本地模型" value="local" />
                <el-option label="API模型" value="api" />
              </el-select>
              <div class="form-tip">使用本地AI模型还是调用远程API</div>
            </el-form-item>
            
            <el-form-item label="API密钥" prop="aiApiKey" :required="aiSettings.enableAiAnalysis && aiSettings.aiModelType === 'api'">
              <el-input 
                v-model="aiSettings.aiApiKey" 
                type="password" 
                placeholder="请输入AI服务API密钥"
                :disabled="!aiSettings.enableAiAnalysis || aiSettings.aiModelType !== 'api'"
              />
              <div class="form-tip">远程AI服务的API密钥</div>
            </el-form-item>
            
            <el-form-item label="API端点" prop="aiApiEndpoint" :required="aiSettings.enableAiAnalysis && aiSettings.aiModelType === 'api'">
              <el-input 
                v-model="aiSettings.aiApiEndpoint" 
                placeholder="请输入AI服务API端点"
                :disabled="!aiSettings.enableAiAnalysis || aiSettings.aiModelType !== 'api'"
              />
              <div class="form-tip">远程AI服务的API端点地址</div>
            </el-form-item>
            
            <el-form-item label="风险评估阈值" prop="riskThreshold" :required="aiSettings.enableAiAnalysis">
              <el-slider 
                v-model="aiSettings.riskThreshold" 
                :min="1" 
                :max="10" 
                :step="0.1"
                show-input
                :disabled="!aiSettings.enableAiAnalysis"
              />
              <div class="form-tip">AI风险评估的阈值，高于此值的漏洞将被标记为高风险</div>
            </el-form-item>
            
            <el-form-item label="生成详细建议" prop="generateDetailedSuggestions" :required="aiSettings.enableAiAnalysis">
              <el-switch 
                v-model="aiSettings.generateDetailedSuggestions" 
                :disabled="!aiSettings.enableAiAnalysis"
              />
              <div class="form-tip">是否生成详细的修复建议，会增加AI处理时间</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 关于 -->
        <el-tab-pane label="关于" name="about">
          <div class="about-section">
            <div class="about-logo">
              <svg width="80" height="80" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
                <circle cx="50" cy="50" r="45" fill="#1890ff" opacity="0.2"/>
                <path d="M50,10 L90,50 L50,90 L10,50 Z" fill="#1890ff"/>
                <path d="M50,25 L75,50 L50,75 L25,50 Z" fill="white"/>
              </svg>
            </div>
            
            <div class="about-info">
              <h2>漏洞扫描与攻击路径分析平台</h2>
              <p class="version">版本: 1.0.0</p>
              <p class="description">
                一款集成漏洞扫描、风险评估和攻击路径分析的综合安全测试平台，
                支持多种漏洞检测、AI风险评估和交互式攻击路径可视化。
              </p>
              <div class="tech-stack">
                <h3>技术栈</h3>
                <div class="tech-tags">
                  <el-tag>Vue 3</el-tag>
                  <el-tag>Element Plus</el-tag>
                  <el-tag>Flask</el-tag>
                  <el-tag>SQLAlchemy</el-tag>
                  <el-tag>Celery</el-tag>
                  <el-tag>NetworkX</el-tag>
                  <el-tag>LightGBM</el-tag>
                  <el-tag>ECharts</el-tag>
                  <el-tag>Cytoscape.js</el-tag>
                </div>
              </div>
              <div class="license">
                <p>开源协议: MIT License</p>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 组件状态
const activeTab = ref('basic')
const isSaving = ref(false)
const basicFormRef = ref(null)
const scanFormRef = ref(null)
const notificationFormRef = ref(null)
const aiFormRef = ref(null)

// 基本配置
const basicSettings = reactive({
  apiEndpoint: 'http://localhost:5000/api',
  scanTimeout: 60,
  autoRefresh: true,
  refreshInterval: 30,
  resultRetentionDays: 30,
  themeMode: 'auto'
})

// 扫描配置
const scanSettings = reactive({
  defaultScanDepth: 2,
  concurrentScans: 5,
  requestTimeout: 30,
  retryCount: 1,
  userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
  useProxy: false,
  proxyServer: ''
})

// 通知配置
const notificationSettings = reactive({
  notifyOnScanComplete: true,
  notifyHighRisk: true,
  emailNotification: false,
  notificationEmail: '',
  webhookNotification: false,
  webhookUrl: ''
})

// AI配置
const aiSettings = reactive({
  enableAiAnalysis: true,
  aiModelType: 'local',
  aiApiKey: '',
  aiApiEndpoint: '',
  riskThreshold: 7.0,
  generateDetailedSuggestions: true
})

// 表单验证规则
const basicRules = {
  apiEndpoint: [
    { required: true, message: '请输入API端点', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL', trigger: 'blur', options: { require_protocol: true } }
  ],
  scanTimeout: [
    { required: true, message: '请输入扫描超时时间', trigger: 'blur' },
    { type: 'number', min: 1, max: 360, message: '扫描超时时间应在1-360分钟之间', trigger: 'blur' }
  ],
  refreshInterval: [
    { required: true, message: '请输入自动刷新间隔', trigger: 'blur', validator: (rule, value, callback) => {
      if (basicSettings.autoRefresh && (!value || value < 5 || value > 300)) {
        callback(new Error('自动刷新间隔应在5-300秒之间'))
      } else {
        callback()
      }
    }}
  ],
  resultRetentionDays: [
    { required: true, message: '请输入结果保留天数', trigger: 'blur' },
    { type: 'number', min: 1, max: 365, message: '结果保留天数应在1-365天之间', trigger: 'blur' }
  ]
}

const scanRules = {
  defaultScanDepth: [
    { required: true, message: '请输入默认扫描深度', trigger: 'blur' },
    { type: 'number', min: 1, max: 5, message: '默认扫描深度应在1-5之间', trigger: 'blur' }
  ],
  concurrentScans: [
    { required: true, message: '请输入并发扫描数', trigger: 'blur' },
    { type: 'number', min: 1, max: 20, message: '并发扫描数应在1-20之间', trigger: 'blur' }
  ],
  requestTimeout: [
    { required: true, message: '请输入请求超时时间', trigger: 'blur' },
    { type: 'number', min: 5, max: 60, message: '请求超时时间应在5-60秒之间', trigger: 'blur' }
  ],
  retryCount: [
    { required: true, message: '请输入重试次数', trigger: 'blur' },
    { type: 'number', min: 0, max: 5, message: '重试次数应在0-5之间', trigger: 'blur' }
  ],
  userAgent: [
    { required: true, message: '请输入User-Agent', trigger: 'blur' }
  ],
  proxyServer: [
    { required: true, message: '请输入代理服务器地址', trigger: 'blur', validator: (rule, value, callback) => {
      if (scanSettings.useProxy && !value) {
        callback(new Error('请输入代理服务器地址'))
      } else if (scanSettings.useProxy && value && !isValidProxy(value)) {
        callback(new Error('请输入有效的代理服务器地址，格式：http://username:password@host:port'))
      } else {
        callback()
      }
    }}
  ]
}

const notificationRules = {
  notificationEmail: [
    { required: true, message: '请输入通知邮箱地址', trigger: 'blur', validator: (rule, value, callback) => {
      if (notificationSettings.emailNotification && !value) {
        callback(new Error('请输入通知邮箱地址'))
      } else if (notificationSettings.emailNotification && value && !isValidEmail(value)) {
        callback(new Error('请输入有效的邮箱地址'))
      } else {
        callback()
      }
    }}
  ],
  webhookUrl: [
    { required: true, message: '请输入Webhook URL', trigger: 'blur', validator: (rule, value, callback) => {
      if (notificationSettings.webhookNotification && !value) {
        callback(new Error('请输入Webhook URL'))
      } else if (notificationSettings.webhookNotification && value && !isValidUrl(value)) {
        callback(new Error('请输入有效的URL'))
      } else {
        callback()
      }
    }}
  ]
}

const aiRules = {
  aiApiKey: [
    { required: true, message: '请输入AI服务API密钥', trigger: 'blur', validator: (rule, value, callback) => {
      if (aiSettings.enableAiAnalysis && aiSettings.aiModelType === 'api' && !value) {
        callback(new Error('请输入AI服务API密钥'))
      } else {
        callback()
      }
    }}
  ],
  aiApiEndpoint: [
    { required: true, message: '请输入AI服务API端点', trigger: 'blur', validator: (rule, value, callback) => {
      if (aiSettings.enableAiAnalysis && aiSettings.aiModelType === 'api' && !value) {
        callback(new Error('请输入AI服务API端点'))
      } else if (aiSettings.enableAiAnalysis && aiSettings.aiModelType === 'api' && value && !isValidUrl(value)) {
        callback(new Error('请输入有效的URL'))
      } else {
        callback()
      }
    }}
  ],
  riskThreshold: [
    { required: true, message: '请设置风险评估阈值', trigger: 'blur', validator: (rule, value, callback) => {
      if (aiSettings.enableAiAnalysis && (!value || value < 1 || value > 10)) {
        callback(new Error('风险评估阈值应在1-10之间'))
      } else {
        callback()
      }
    }}
  ]
}

// 初始化
onMounted(() => {
  loadSettings()
})

// 加载设置
const loadSettings = () => {
  try {
    // 从localStorage加载设置
    const savedBasicSettings = localStorage.getItem('basicSettings')
    const savedScanSettings = localStorage.getItem('scanSettings')
    const savedNotificationSettings = localStorage.getItem('notificationSettings')
    const savedAiSettings = localStorage.getItem('aiSettings')
    
    if (savedBasicSettings) {
      Object.assign(basicSettings, JSON.parse(savedBasicSettings))
    }
    
    if (savedScanSettings) {
      Object.assign(scanSettings, JSON.parse(savedScanSettings))
    }
    
    if (savedNotificationSettings) {
      Object.assign(notificationSettings, JSON.parse(savedNotificationSettings))
    }
    
    if (savedAiSettings) {
      Object.assign(aiSettings, JSON.parse(savedAiSettings))
    }
  } catch (error) {
    console.error('加载设置失败:', error)
    ElMessage.error('加载设置失败，使用默认配置')
  }
}

// 保存设置
const saveSettings = async () => {
  try {
    // 验证当前标签页的表单
    let isValid = true
    
    if (activeTab.value === 'basic' && basicFormRef.value) {
      isValid = await basicFormRef.value.validate()
    } else if (activeTab.value === 'scan' && scanFormRef.value) {
      isValid = await scanFormRef.value.validate()
    } else if (activeTab.value === 'notification' && notificationFormRef.value) {
      isValid = await notificationFormRef.value.validate()
    } else if (activeTab.value === 'ai' && aiFormRef.value) {
      isValid = await aiFormRef.value.validate()
    }
    
    if (!isValid) {
      return
    }
    
    isSaving.value = true
    
    // 保存到localStorage
    localStorage.setItem('basicSettings', JSON.stringify(basicSettings))
    localStorage.setItem('scanSettings', JSON.stringify(scanSettings))
    localStorage.setItem('notificationSettings', JSON.stringify(notificationSettings))
    localStorage.setItem('aiSettings', JSON.stringify(aiSettings))
    
    // 这里可以添加调用API保存到服务器的逻辑
    // await apiService.saveSettings({
    //   basic: basicSettings,
    //   scan: scanSettings,
    //   notification: notificationSettings,
    //   ai: aiSettings
    // })
    
    // 处理主题模式变更
    if (activeTab.value === 'basic') {
      applyThemeMode(basicSettings.themeMode)
    }
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    ElMessage.success('配置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error(`保存设置失败: ${error.message || '未知错误'}`)
  } finally {
    isSaving.value = false
  }
}

// 应用主题模式
const applyThemeMode = (mode) => {
  if (mode === 'auto') {
    const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
    document.documentElement.classList.toggle('dark', isDarkMode)
  } else {
    document.documentElement.classList.toggle('dark', mode === 'dark')
  }
}

// 验证工具函数
const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

const isValidUrl = (url) => {
  try {
    new URL(url)
    return true
  } catch (error) {
    return false
  }
}

const isValidProxy = (proxy) => {
  try {
    // 简单的代理格式验证，实际应用中可能需要更复杂的验证
    const proxyRegex = /^https?:\/\/(?:[^:@\n]+:[^:@\n]+@)?[^:@\n]+:\d+$/i
    return proxyRegex.test(proxy)
  } catch (error) {
    return false
  }
}
</script>

<style scoped>
.settings-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.settings-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.settings-tabs {
  margin-top: 20px;
}

.settings-form {
  width: 100%;
  max-width: 600px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.unit {
  margin-left: 8px;
  color: #606266;
}

.about-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.about-logo {
  margin-bottom: 30px;
}

.about-info {
  text-align: center;
  max-width: 600px;
}

.about-info h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
}

.version {
  color: #1890ff;
  font-size: 16px;
  margin: 0 0 20px 0;
}

.description {
  color: #606266;
  line-height: 1.6;
  margin: 0 0 30px 0;
}

.tech-stack h3 {
  color: #303133;
  font-size: 16px;
  margin: 0 0 15px 0;
}

.tech-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
  margin-bottom: 20px;
}

.license {
  color: #909399;
  font-size: 14px;
}

/* 适配深色模式 */
:deep(.dark) .settings-card {
  background-color: #1f2937;
  border-color: #374151;
}

:deep(.dark) .el-form-item__label {
  color: #d1d5db;
}

:deep(.dark) .el-input__wrapper {
  background-color: #111827;
  border-color: #374151;
}

:deep(.dark) .el-input__inner {
  color: #f3f4f6;
}
</style>